package com.ruoyi.iot.dataprocessing.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.device.api.RemoteDeviceService;
import com.ruoyi.device.api.domain.DeviceOnline;
import com.ruoyi.iot.dataprocessing.domain.SensorMessage;
import com.ruoyi.iot.dataprocessing.enums.DataAssemblyEnum;
import com.ruoyi.iot.dataprocessing.service.AsyncService;
import com.ruoyi.iot.dataprocessing.service.ISensorMessageService;
import com.ruoyi.iot.dataprocessing.strategy.SensorMessageStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AsyncServiceImpl implements AsyncService {

    private static final Logger log = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Autowired
    private ISensorMessageService sensorMessageService;
    @Autowired
    private RemoteDeviceService remoteDeviceService;
    @Autowired
    private PushService pushService;

    @Autowired
    private SensorMessageStrategy sensorMessageStrategy;


    @Override
    @Async("asyncServiceExecutor")
    public void executeAsync(String topic, byte[] payload) {
        JSONObject jsonObject = JSONObject.parseObject(new String(payload));
        SensorMessage sensorMessage = sensorMessageStrategy.getSensorMessage(jsonObject.getIntValue("type"), payload);
//        SensorMessage sensorMessage = DataAssemblyEnum.getSensorMessageByPaload(jsonObject.getIntValue("type"), payload);
        if (sensorMessage == null) {
            return;
        }
        sensorMessageService.insertSensorMessage(sensorMessage);

        pushService.push(sensorMessage.getDeviceType(),sensorMessage.getCustomerId(), payload);
    }

    @Override
    @Async("asyncServiceExecutor")
    public void updateDeviceStatus(String clientId, String status) {
        DeviceOnline deviceOnline = new DeviceOnline();
        deviceOnline.setDeviceNo(clientId);
        deviceOnline.setIsOnline(status);
        deviceOnline.setCreateTime(new Date());
        R<Boolean> booleanR = remoteDeviceService.updateDeviceStatus(deviceOnline, SecurityConstants.INNER);
    }
}